<template>
    <div class="app-container">
      <!-- Header Section -->
      <header class="header">
        <div>
          <div class="header-title">{{currentAlgorithm?.name}}</div>
          <div class="header-subtitle">{{currentAlgorithm?.description}}</div>
        </div>
        <div>
          <el-button style="position: absolute;right: 0;top: 50%;transform: translate(0,-50%);" type="primary" @click="backHome()">返回首页</el-button>
        </div>
      </header>
      <main class="main">
        <div class="main-top">
          <div class="top-left">
            <div class="image-container">
                <!-- 图片 -->
                  <el-image
                      :src="sampleImageUrl"
                      style="width: 100%; height: 100%"
                      fit="contain"
                      @load="handleImageLoad"
                      @click="openDrawer"
                    />
                  <!-- Canvas 画框 -->
                  <canvas ref="canvasRef" class="bounding-box-canvas"></canvas>

                  <el-drawer v-model="drawer"  direction="ltr" :with-header="false" size="60%" style="background: rgba(0, 0, 0, 0.4) !important; padding: 20px;"  @update:modelValue="handleCloseDrawer">
                    <div class="image-containerOne" @wheel="handleWheel">
                      <el-image 
                      ref="imageRef"
                      style="width: 100%;height:100%;"
                      :src="DrawerSampleImageUrl" 
                      @load="handleImageLoadOne"
                      fit="contain " 
                      />  
                    <canvas ref="canvasRefOne" class="bounding-box-canvas"></canvas>
                    </div>
                  </el-drawer>
              </div>
        </div>
        <div class="top-right" style="height: 100%; position: relative;">
  <div style="color: white;font-size: 1.3rem;line-height: 2rem;margin-bottom: 1rem; text-align: center;font-weight: bold;background-color: rgba(149, 149, 150, 1);padding: 1rem;">
    识别结果
  </div>
  <!-- :style="{ overflowY: algorithmResultMessageList?.length > 5 ? 'scroll' : 'hidden'}" -->
  <div style="height: calc(100% - 120px); padding-bottom: 10px; overflow: auto;"    >
    <div v-if="Analyse == true" style="color:lightblue;margin-top: 1rem;font-size: 1.2rem;text-align: center;">
      解析中
    </div>
    <div v-else-if="algorithmResultMessageList?.length === 0"  style="color:lightgreen;margin-top: 1rem;font-size: 1.2rem;text-align: center;">
      未发现匹配的结果目标
    </div>
    <div v-else>
      <table style="width: 100%; border-collapse: collapse;">
        <thead>
          <tr>
            <th style="text-align: center;color: white;">序号</th>
            <th style="text-align: center;color: white;">标签</th>
            <th style="text-align: center;color: white;">置信度</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in algorithmResultMessageList" :key="item.id" style="border: none;">
            <td style="padding-top: 10px;text-align: center;color: white;">{{ item.id }}</td>
            <td style="padding-top: 10px;text-align: center;color: white;">{{ item.code }}</td>
            <td style="padding-top: 10px;text-align: center;color: white;">{{ (item.confidence*100).toFixed(1) }}%</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</div>

      </div>
        <div class="main-bottom">
          <div class="bottom-left">
              <div class="bottom-min1 , box"  id="box1">
                <el-image
                  @click="changeImageResultOne(); selectBox(1)"
                  style="width: 100%; height: 100%"
                  :src="smallSample"
                  fit="cover"
                />


              </div>
              <div class="bottom-min2 , box"  id="box2">
                <el-image
                  v-if="selsetSampleImageUrl"
                  style="width: 100%; height: 100%"
                  :src="selsetSampleImageUrl"
                  fit="cover"
                />
                <div v-if="selsetSampleImageUrl" style="position: absolute;left: 0;top: 0;width: 100%;height: 100%;background-color: rgba(255, 255, 255,0.5);" @click="submitSelectImgResultOne();selectBox(2)"></div>
                <div style="position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);color: black;font-weight:600"  @click="SelectImgDialog()">
                  <el-icon  style="cursor: pointer;"  size="30"><Picture /></el-icon>
                  <div  class="textChangeColor"  style="cursor: pointer;"  v-if="selsetSampleImageUrl">重新选择</div>
                  <div  class="textChangeColor" style="cursor: pointer;"    v-else>选择图片</div>

                </div>
              </div>
              <div class="bottom-min3 , box"  id="box3">
                <el-image
                  v-if="updataSampleUrl"
                  style="width: 100%; height: 100%"
                  :src="updataSampleUrl"
                  
                  fit="cover"
                />
                <div v-if="updataSampleUrl" style="position: absolute;left: 0;top: 0;width: 100%;height: 99%;background-color: rgba(255, 255, 255,0.5);"  @click="updataSampleUrlResultOne() ; selectBox(3)"></div>
                  <div  style="position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);color: black;font-weight:600" @click="uploadImages()">
                    <img style="width: 40px;height: auto;cursor: pointer;" src="../assets/image/updata.png" alt="" >
                    <div  class="textChangeColor"  v-if="updataSampleUrl" style="font-size: 15px;line-height: 15px;cursor: pointer;">重新上传</div>
                    <div  class="textChangeColor" v-else  style="font-size: 15px;line-height: 15px;cursor: pointer;">图片上传</div>
                  </div>
              </div>
          </div>
          <div class="bottom-right">
              <!-- 这里是触摸more显示出来的所有选项 -->
              <div v-if="checkAlgorithm" @mouseenter="checkAlgorithm = true" @mouseleave="checkAlgorithm = false" 
                  style="width: 80%;position: absolute;background-color:#0c294c;z-index: 999;bottom:70%;left: 10%;padding: 10px;max-width: 60vh;">
                <div
                  v-for="item in formattedMenuItems"
                  :key="item.id"
                  :id="item.href.slice(1)"
                  class="menu-item"
                >
              <!-- 场景标题和描述 -->
                <div class="scene-title" style="cursor: default;">
                  <template v-if="item.isSpecial">
                    <span
                      @click="navigateTo(item.href)"
                      style="color: #42a5f5; text-decoration: underline; cursor: pointer;"
                    >
                    {{ item.name }}
                    </span>
                  </template>
                  <template v-else>
                    {{ item.name }}
                  </template>
                </div>
              <!-- 算法展示网格 -->
                <div class="algorithm-grid">
                <div
                  v-for="algorithm in item.algorithms"
                  :key="algorithm.id"
                  class="algorithm-item"
                >
              <span type="primary"  class="algorithm-name" @click="changeAlgor(algorithm)" style="cursor: pointer;">{{ algorithm.name }}</span>
              </div>
              </div>
              </div>
              </div>

              <div class="bottom-right-left"> 
                <img style="width: 60%;height: auto;position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);" src="../assets//image/algorith.png" alt="">
              </div>
              <div class="bottom-right-middle">
                <div style="width: 100%; position: absolute;top: 50%;left: 50%;transform:translate(-50%,-50%);">
                  <div style="display: flex;">
                    <img src="../assets//image/al.png"  style="width: 1rem;height: auto;"  alt="">
                    <div style="font-size:1rem;margin-left: 0.5rem;">{{currentAlgorithm?.scenarioName}}</div> 
                  </div>
                <div style="font-size:1.2rem;">{{currentAlgorithm?.name}}</div>
                </div>
              </div>
              <div class="bottom-right-right" @mouseenter="checkAlgorithm = true" @mouseleave="checkAlgorithm = false"  @click="checkAlgorithm = true">
                <div style="position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);">
                    <div class="moreChange" style="font-size: 2.3rem; cursor: pointer;">more</div>
                </div>
              </div>
          </div>
        </div>
      </main>
  
    </div>
          <!-- 上传图片弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        title="图片上传"
        width="500"
        >
        <div  v-loading="upImage">
          <div style="color: black;margin-top:0.5rem;">
            <el-icon style="color: #FF9F00;vertical-align: baseline ;"><Warning /></el-icon>
            <span  style="margin-left: 1rem;">单次仅限上传1图片</span>
          </div>
          <div style="color: black;margin:0.5rem 0">
            <el-icon style="color: #FF9F00;vertical-align: baseline ;"><Warning /></el-icon>

            <span  style="margin-left: 1rem;">上传图片大小不要超过4M</span>
            </div>
          <div style="color: black;margin: 0.5rem 0;">
            <el-icon style="color: #FF9F00;vertical-align: baseline ;"><Warning /></el-icon>

            <span style="margin-left: 1rem;">格式支持PNG ，JPG ，JPEG ，BMP
            </span>
             </div>   
        <el-upload
        v-model:file-list="fileList"
        :auto-upload="false"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :limit="1"
        multiple
        accept="image/*"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>
      <el-dialog v-model="dialog">
        <img style="width: 100%;" :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
      </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="upLoadImage">
          上传
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 选择图片的弹窗 -->
  <el-dialog
    v-model="SelectImgDialogVisible"
    title="请选择图片查看效果"
    width="500"
  >
  <!-- 图片数据 -->
  <div  v-loading="seImage" style="width: 100%;">
    <div style="font-size: 1rem;font-weight: bold;">效果良好的图片示例</div>
    <!-- 展示好的图片 -->
    <div style="display: flex; flex-wrap: wrap; gap: 16px; margin-bottom: 24px;">
      <div
        v-for="item in imagesStatusZeroList"
        :key="item.id"
        style="width: calc(50% - 8px);"
      >
        <div
          style="width: 100%; height: 100px; cursor: pointer;"
          @click="selectImage(item)"
          @dblclick = "dblSelectImage(item)"
          :style="{ 'border': selectImageId === item.id ? '5px solid skyblue' : '5px solid white' }"
        >
          <img
            style="width: 100%; height: 100%; object-fit: cover;"
            :src="item.imageUrl"
            alt="image"
          />
        </div>
      </div>
    </div>

    <!-- 展示不好的图片 -->
    <div style="display: flex; flex-direction: column; gap: 16px;">
      <div style="font-size: 1rem;font-weight: bold;">效果较差的图片示例</div>
      <div
        v-for="item in imagesStatusOneList"
        :key="item.id"
        style="display: flex; align-items: center; gap: 16px;"
      >
        <!-- 左侧图片 -->
        <div
          style="width: 180px; height: 100px; cursor: pointer;"
          @click="selectImage(item)"
          @dblclick = "dblSelectImage(item)"
          :style="{ 'border': selectImageId === item.id ? '5px solid skyblue' : '5px solid white' }"
        >
          <img
            style="width: 100%; height: 100%; object-fit: cover;"
            :src="item.imageUrl"
            alt="image"
          />
        </div>
        <!-- 右侧描述 -->
        <div style="flex: 1; font-size: 14px; color: #333;">
          <span style="color: red;">原因：</span>{{ item.description || '无描述信息' }}
        </div>
      </div>
    </div>
  </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="SelectImgDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitSelectImg()">
          选择
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 登录弹窗 -->
  <el-dialog
          v-model="LoginVisible"
          width="500"
      >
      <LoginPage @close1="handleClose"></LoginPage>
      </el-dialog>
  </template>
  
  <script lang="ts" setup> 
  import { useAlgorStore } from '@/stores/algorothm';
  import { ref ,onMounted,computed,nextTick} from 'vue'
  import { useRoute ,useRouter} from 'vue-router'
  import { Plus,Picture,Warning} from '@element-plus/icons-vue'
  import {  type UploadProps,type UploadFile ,ElMessage, type UploadInstance,  type UploadRawFile } from 'element-plus';
  import request from '@/utils/request'
  import LoginPage from './LoginPage.vue';
  import { genFileId } from 'element-plus'
  // 这里是跟canvas绘制相关的
  const canvasRef = ref<HTMLCanvasElement | null>(null);
  const canvasRefOne = ref<HTMLCanvasElement | null>(null);

  const algorithmResult = ref([])//接收路由的算法坐标值
  const drawer = ref(false)


  const drawBoxes = async () => {
    clearCanvas()
  await nextTick(); // 确保 DOM 渲染完成

  const canvas = canvasRef.value;
  if (!canvas) {
    console.warn("Canvas 还未初始化");
    return;
  }
  const imgElement = canvas.closest(".image-container")?.querySelector("img");
  if (!imgElement) {
    console.warn("未找到图片元素");
    return;
  }

  if (!canvas || !imgElement) return;

  // 获取图片的实际尺寸
  const { naturalWidth, naturalHeight } = imgElement;
  
  const { width, height, left, top } = imgElement.getBoundingClientRect();

  // 计算缩放比例
  const scaleX = width / naturalWidth;
  const scaleY = height / naturalHeight;

  
  const adjustedScaleX = (canvas.width / naturalWidth);
  
  
  const adjustedScaleY = (canvas.height / naturalHeight);


  if(scaleX > scaleY){
    // 设置 Canvas 尺寸  
  canvas.width = naturalWidth * scaleY;
  canvas.height = height;
  canvas.style.left = (width - naturalWidth * scaleY) / 2 +'px';
  canvas.style.top = 0 + 'px';
  }else {
      // 设置 Canvas 尺寸  
  canvas.width = width;
  canvas.height = naturalHeight * scaleX;
  canvas.style.top = (height - naturalHeight * scaleX) / 2 +'px';
  canvas.style.left = 0 + 'px';
  }
  const ctx = canvas.getContext("2d");
  if (!ctx) {
    console.error("无法获取 Canvas 上下文");
    return;
  }
  ctx.clearRect(0, 0, canvas.width, canvas.height);  

  // 遍历 algorithmResultImg，绘制矩形框
  algorithmResult.value.forEach(({ x, y, x2, y2, code ,id}) => {
    ctx.strokeStyle = "red";
    ctx.lineWidth = 2;
    
  if(scaleX > scaleY){
    ctx.strokeRect(x * adjustedScaleX, y * adjustedScaleX, (x2 - x) * adjustedScaleX, (y2 - y) * adjustedScaleX);
  }else{
    ctx.strokeRect(x * adjustedScaleY, y * adjustedScaleY, (x2 - x) * adjustedScaleY, (y2 - y) * adjustedScaleY);
  }
    ctx.fillStyle = "red";
    ctx.font = "14px Arial";
    const textX = x * adjustedScaleX; // 让文本稍微偏移，避免贴边
    const textY = y * adjustedScaleY; // 让文本稍微偏移，避免贴边
    ctx.textAlign = "left"; // 左对齐
    ctx.textBaseline = "top"; // 顶部对齐
    ctx.fillText(`${id}`, textX, textY);
  });
};


const drawBoxesOne = async () => {
    clearCanvasOne()
  await nextTick(); // 确保 DOM 渲染完成

  const canvas = canvasRefOne.value;
  if (!canvas) {
    console.warn("Canvas 还未初始化");
    return;
  }
  const imgElement = canvas.closest(".image-containerOne")?.querySelector("img");
  if (!imgElement) {
    console.warn("未找到图片元素");
    return;
  }

  if (!canvas || !imgElement) return;

  // 获取图片的实际尺寸
  const { naturalWidth, naturalHeight } = imgElement;
  
  const { width, height, left, top } = imgElement.getBoundingClientRect();
  
   // 计算缩放比例
  const scaleX = width / naturalWidth;
  const scaleY = height / naturalHeight;

  
  const adjustedScaleX = (canvas.width / naturalWidth);
  
  
  const adjustedScaleY = (canvas.height / naturalHeight);


  if(scaleX > scaleY){
    // 设置 Canvas 尺寸  
  canvas.width = naturalWidth * scaleY;
  canvas.height = height;
  canvas.style.left = (width - naturalWidth * scaleY) / 2 +'px';
  canvas.style.top = 0 + 'px';
  }else {
      // 设置 Canvas 尺寸  
  canvas.width = width;
  canvas.height = naturalHeight * scaleX;
  canvas.style.top = (height - naturalHeight * scaleX) / 2 +'px';
  canvas.style.left = 0 + 'px';
  }
  const ctx = canvas.getContext("2d");
  if (!ctx) {
    console.error("无法获取 Canvas 上下文");
    return;
  }
  ctx.clearRect(0, 0, canvas.width, canvas.height);  

  // 遍历 algorithmResultImg，绘制矩形框
  algorithmResult.value.forEach(({ x, y, x2, y2, code,id }) => {
    ctx.strokeStyle = "red";
    ctx.lineWidth = 2;
    if(scaleX > scaleY){
    ctx.strokeRect(x * adjustedScaleX, y * adjustedScaleX, (x2 - x) * adjustedScaleX, (y2 - y) * adjustedScaleX);
  }else{
    ctx.strokeRect(x * adjustedScaleY, y * adjustedScaleY, (x2 - x) * adjustedScaleY, (y2 - y) * adjustedScaleY);
  }

    ctx.fillStyle = "red";
    ctx.font = "16px Arial";
    const textX = x * adjustedScaleX; // 让文本稍微偏移，避免贴边
    const textY = y * adjustedScaleY + 20; // 让文本稍微偏移，避免贴边
    ctx.textAlign = "left"; // 左对齐
    ctx.textBaseline = "top"; // 顶部对齐
    ctx.fillText(`${id}`, textX, textY);

  });
};

// 清理canvas相关数据
const clearCanvas = () => {
  const canvas = canvasRef.value;
  if (!canvas) return;

  const ctx = canvas.getContext("2d");
  if (ctx) {
    const { width, height } = canvas;
    ctx.clearRect(0, 0, width, height);
    canvas.width = width;
    canvas.height = height;
  }
};

const clearCanvasOne = () => {
  const canvas = canvasRefOne.value;
  if (!canvas) return;

  const ctx = canvas.getContext("2d");
  if (ctx) {
    const { width, height } = canvas;
    ctx.clearRect(0, 0, width, height);
    canvas.width = width;
    canvas.height = height;
  }
};


  const sampleImage = ref()//用来存储选择的image的图片信息
  const sampleImageUrl = ref()//用来存储选择的image的图片的路径
  const smallSample = ref()//左下角的示例图片
  const selsetSampleImageUrl = ref()//用来存储选择的图片
  const updataSampleUrl = ref()//用来存储上传图片的路径
  const algorithmResultImg = ref()//算法返回的结果
  const algorithmResultMessageList = ref<any>()//算法返回的结果执信度
  const dialogVisible = ref(false)
  const SelectImgDialogVisible = ref(false);
  const dialog = ref(false)
  const fileList = ref<UploadFile[]>([]);//上传图片
  const route =useRoute()
  const router =useRouter()
  const checkAlgorithm =ref(false);//切换算法的弹窗
  const pageScenarioID = ref()//这个是当前页面算法的id
  const dialogImageUrl = ref('')
  const selectImageId = ref()//选择图片时候使用的id
  const LoginVisible = ref(false)//登录弹窗控制
    // Store 数据
  const algorStore = useAlgorStore();
    // 这个是所有的场景信息喝算法信息
    const formattedMenuItems = computed(() => {
  const baseItems = AllAlgorithmAndAlgorithmScenario.value?.algorithmViews?.map((item: any, index: number) => ({
    id: item.scenario.id || "N/A",
    name: item.scenario.scenarioName || "未知场景",
    description: item.scenario.scenarioDescription || "无描述",
    href: `#part${index}`,
    algorithms: item.algorithms.map((algorithm: any) => ({
      id: algorithm?.algorithm?.id || "N/A",
      scenarioID: algorithm?.algorithm?.scenarioID || "N/A",
      name: algorithm?.algorithm?.algorithmName || "未知算法",
      coverUrl: algorithm?.algorithm?.coverUrl || "",
      description: algorithm?.algorithm?.description || "无描述",
      exampleUrl: algorithm?.algorithm?.exampleUrl || "",
      images: algorithm?.images || [],
      result: algorithm?.algorithm?.algorithmResult || '',
    })),
  })) || [];
  // 添加大模型配置特殊菜单项
  if (AllAlgorithmAndAlgorithmScenario.value?.largeModel) {
    console.log('largeModel:', AllAlgorithmAndAlgorithmScenario.value?.largeModel);
    baseItems.push({
      id: 'large-model-config',
      name: AllAlgorithmAndAlgorithmScenario.value.largeModel.scenarioName,
      description: AllAlgorithmAndAlgorithmScenario.value.largeModel.algorithmDesc,
      href: '/BigModel',
      isSpecial: true, // 标记为特殊菜单项
      algorithms: [
      ]
    });
  }
  return baseItems;
});


const navigateTo = (url:any) => {

  router.push({
      path: "/bigModel",
      query: {
        scenarioID: AllAlgorithmAndAlgorithmScenario.value.largeModel.id,
        name: AllAlgorithmAndAlgorithmScenario.value.largeModel.algorithmName,
        description: AllAlgorithmAndAlgorithmScenario.value.largeModel.algorithmDesc,
        scenarioName:AllAlgorithmAndAlgorithmScenario.value.largeModel.scenarioName
      },
    });

};


// 这个是算法
const algorithms = computed(() =>
  formattedMenuItems.value.flatMap((scene:any) =>
    scene.algorithms.map((algorithm:any) => ({
      ...algorithm,
      scenarioName: scene.name, // 关联场景名称
    }))
  )
);

const selectBox = (boxNumber:number) => {
  algorithmResult.value = []    
  // 先进行清理
    clearCanvas()
    nextTick()
  if(boxNumber ==1 && !changeAlgorithmFlag.value){
    console.log('默认选中第一项，未算法');

      algorithmResult.value = JSON.parse(JSON.parse(route.query.result as string)).result;
      algorithmResultMessageList.value = JSON.parse(JSON.parse(route.query.result as string)).result;
    // **调用绘制方法**
    drawBoxes();
    }else if(boxNumber ==1 && changeAlgorithmFlag.value){
      console.log('默认选中第一项，切换算法');
      
      sampleImageUrl.value =  changeAlgorithm.value.exampleUrl
      algorithmResult.value = JSON.parse(changeAlgorithm.value.result).result;
      algorithmResultMessageList.value = JSON.parse(changeAlgorithm.value.result).result;
    // **调用绘制方法**
    drawBoxes();
    }
  else if(boxNumber == 2) { 
    algorithmResult.value = selectImgResult.value; 
    console.log(selectImgResult.value);
    algorithmResultMessageList.value = selectImgResult.value
    // **调用绘制方法**
    drawBoxes();
  }else if(boxNumber == 3){
   algorithmResult.value  =  uploadImagesReult.value
   algorithmResultMessageList.value = uploadImagesReult.value

   drawBoxes()
  }
  
  // 清除所有选中的样式
  const boxes = document.querySelectorAll('.box');
  boxes.forEach(box => {
    box.classList.remove('selected');
  });

  // 为选中的div添加选中样式
  const selectedBox = document.getElementById(`box${boxNumber}`);
  if(selectedBox){
    selectedBox.classList.add('selected');
  }
}

// 根据当前传过来的id进行筛选
const currentAlgorithm = computed(() =>
  algorithms.value.find((algorithm:any) => algorithm.id == pageScenarioID.value) || null
);

const imagesStatusOneList = computed(() => {
  // 检查 currentAlgorithm 是否存在，并返回过滤后的数组或空数组
  return currentAlgorithm.value?.images.filter((img: any) => img.status == 1) || [];
});

const imagesStatusZeroList = computed(() => {
  // 检查 currentAlgorithm 是否存在，并返回过滤后的数组或空数组
  return currentAlgorithm.value?.images.filter((img: any) => img.status == 0) || [];
});


//切换当前算法
const changeAlgorithmFlag = ref(false)

const changeAlgorithm = ref()
const changeAlgor = (item: any) => {
  console.log(1111111,item);
  
  changeAlgorithmFlag.value = true
  changeAlgorithm.value = item

  // 隐藏算法选择弹窗
  checkAlgorithm.value = false;

  // 清理 Canvas 和旧数据
  clearCanvas();
  algorithmResult.value = []; // 清空结果
  algorithmResultMessageList.value = ''; // 清空结果数据
  selectImgResult.value = [];//清空结果数据
  selsetSampleImageUrl.value = ''; // 清空选择的图片
  updataSampleUrl.value = ''; // 清空上传的图片
  // 更新当前算法的 ID
  pageScenarioID.value = item.id;

  // 将当前算法的 ID 存储到 localStorage
  localStorage.setItem('currentScenarioID', item.id);

  // 更新左下方的示例图片
  smallSample.value = item.exampleUrl;  
  // 更新当前算法的数据
  if (item.result) {    
    // 更新大图片
    sampleImageUrl.value = item.exampleUrl;
    const img = new Image()
    img.src = sampleImageUrl.value;
    img.onload = () => { 
          nextTick(()=>{
        // 解析算法结果
       algorithmResult.value = JSON.parse(item.result).result;
       algorithmResultMessageList.value = JSON.parse(item.result).result;
        // 确保图片加载完成后再绘制 Canvas
      drawBoxes();          
          })
        }
  } else {
    // 如果没有算法结果，清空相关数据
    algorithmResultImg.value = '';
    algorithmResultMessageList.value = '';
  }

  // 切换到第一个盒子（示例图片）
  selectBox(1);
};


  // 删除逻辑
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
}
const upload = ref<UploadInstance>()
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}

// 预览逻辑
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialog.value = true
}

// 点击选择图片触发的逻辑
const  SelectImgDialog = () => {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'; // 检查本地存储中的登录状态
  if(isLoggedIn){
    SelectImgDialogVisible.value = true
  }else {
    ElMessage.error("当前为未登录状态，请登录后再试吧");
    LoginVisible.value = true;
  }
}

// 点击上传图片触发的逻辑
const  uploadImages = () => {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'; // 检查本地存储中的登录状态
  if(isLoggedIn){
   dialogVisible.value = true 
  }else {
    ElMessage.error("当前为未登录状态，请登录后再试吧");                                                                 
    LoginVisible.value = true;
  }
}

const handleClose = () => {
  LoginVisible.value = false
}

// 上传逻辑
const upImage = ref(false)
const updataSampleUrlResult = ref()
const updataSampleUrlResultMessage = ref()
const updataSampleUrlResultOne = () => {
  sampleImageUrl.value = updataSampleUrl.value
    if (updataSampleUrlResult) {
      algorithmResultImg.value =updataSampleUrlResult.value//算法返回的结果图片
       algorithmResultMessageList.value = updataSampleUrlResultMessage.value//算法返回的结果执信度
    }
}

const handleImageLoad = () => {
  nextTick(() => {
    drawBoxes();
  });
};

const handleImageLoadOne = () => {
  DrawerSampleImageUrl.value = sampleImageUrl.value
  const img = new Image()
    img.src = DrawerSampleImageUrl.value;
    img.onload = () => { 
      nextTick(() => {
        drawBoxesOne();
      })
    }
};

// 鼠标滚轮事件
const imageScale = ref(1); // 图片缩放比例
const canvasScale = ref(1); // Canvas 缩放比例
const imageRef = ref<any>(null);


const handleWheel = (event: WheelEvent) => {
  event.preventDefault();

  const zoomFactor = 0.1; // 缩放步长
  if (event.deltaY < 0) {
    // 放大
    imageScale.value += zoomFactor;
    canvasScale.value += zoomFactor;
  } else {
    // 缩小（限制最小缩放比例）
    imageScale.value = Math.max(1, imageScale.value - zoomFactor);
    canvasScale.value = Math.max(1, canvasScale.value - zoomFactor);
  }

  // 直接在左上角缩放
  if (imageRef.value) {
    imageRef.value.$el.style.transformOrigin = "0 0"; // 左上角缩放
    imageRef.value.$el.style.transform = `scale(${imageScale.value})`;
  }
  if (canvasRefOne.value) {
    canvasRefOne.value.style.transformOrigin = "0 0"; // 左上角缩放
    canvasRefOne.value.style.transform = `scale(${canvasScale.value})`;
  }
};

// 关闭弹窗执行的相关操作
const handleCloseDrawer = () => {
  clearCanvasOne();

  // 重置缩放比例
  imageScale.value = 1;
  canvasScale.value = 1;

  // 确保 transformOrigin 也恢复
  if (imageRef.value) {
    imageRef.value.$el.style.transformOrigin = "0 0"; // 保证缩放基点不变
    imageRef.value.$el.style.transform = `scale(1)`;
  }

  if (canvasRefOne.value) {
    canvasRefOne.value.style.transformOrigin = "0 0";
    canvasRefOne.value.style.transform = `scale(1)`;
  }

  // 等待 DOM 重新渲染后，再重置图片的 src，避免缩放未生效
  setTimeout(() => {
    if (imageRef.value) {
      imageRef.value.src = "";
      imageRef.value.src = DrawerSampleImageUrl;
    }
  }, 50);
};


const  DrawerSampleImageUrl = ref()
const openDrawer = () => {
  DrawerSampleImageUrl.value = sampleImageUrl.value
    drawer.value = true
    const img = new Image()
    img.src = DrawerSampleImageUrl.value;
    img.onload = () => { 
      nextTick(() => {
        drawBoxesOne();
      })
    }

}

const uploadImagesReult = ref([])
const upLoadImage = async () => {
  algorithmResult.value = []; // 清空结果
  algorithmResultMessageList.value = ''; // 清空结果数据
  selectImgResult.value = [];//清空结果数据
  upImage.value = true
  if (!fileList.value.length) {
    console.error('No files selected.');
    return;
  }
  Analyse.value = true
  const formData = new FormData();
  fileList.value.forEach((file) => {
    if (file.raw instanceof Blob) {
      // 确保 raw 存在并且是 Blob 类型
      formData.append('inputFile', file.raw);   
    } else {
      console.warn('File does not have raw data:', file);
    }
  });
      formData.append('id',pageScenarioID.value);
  try {
    request.post('/algorithm/algorithmAnalysisFile', formData).then((res)=> {
      upImage.value = false
      //提示图片解析成功  
      if(res.data.code === 'success'){    
        upImage.value = false
        updataSampleUrl.value = res.data.primaryImage //原图的url
        // 将默认展示的图片也变成这个
          sampleImageUrl.value = res.data.primaryImage
          const img = new Image();
          img.src = sampleImageUrl.value;
          img.onload = () => { 
            uploadImagesReult.value = res.data.result
            algorithmResult.value = res.data.result
            algorithmResultMessageList.value = uploadImagesReult.value
            Analyse.value = false  
            clearCanvas();              
            drawBoxes();
        }
        ElMessage({
        message: '算法解析成功',
        type: 'success',
  })
       dialogVisible.value = false; // 关闭弹窗
       fileList.value = []
       selectBox(3)
       }  
    });     
  } catch (error) {
    console.error('Upload failed:', error);
    upImage.value = false
  }
};

const selectImage = (item:any) => {
    sampleImage.value = item;
    selectImageId.value = item.id
}

const dblSelectImage = (item:any) => {
  sampleImage.value = item;
    selectImageId.value = item.id
    submitSelectImg()
    selectBox(2)
}

const changeImageResultOne = () => {
  algorithmResult.value = []
    //清除canvas数据
    clearCanvas()
    algorithmResult.value =JSON.parse(JSON.parse(route.query.result as string)).result;
    drawBoxes();
  if (currentAlgorithm.value) {
    sampleImageUrl.value = route.query.exampleUrl
  } else {
    submitSelectImgResultOne();
  }
};

// 上传选中的图片，调用算法
const seImage = ref(false)
const submitSelectImgResult = ref()
const submitSelectImgResultMessage = ref()


const submitSelectImgResultOne = () => {
  sampleImageUrl.value =  sampleImage.value.imageUrl //图片切换
  if (submitSelectImgResult.value) {
    algorithmResultImg.value  = submitSelectImgResult.value 
    algorithmResultMessageList.value = submitSelectImgResultMessage.value
  }
}
const selectImgResult = ref([])
const Analyse = ref(false)
const submitSelectImg = () => {
  Analyse.value = true
  algorithmResult.value = []; // 清空结果
  algorithmResultMessageList.value = []; // 清空结果数据
  selectImgResult.value = [];//清空结果数据

  seImage.value = true
  const formData = new FormData();
  formData.append('id',pageScenarioID.value);
  formData.append('inputFile',sampleImage.value.imageUrl);

  try {
  request.post('/algorithm/algorithmAnalysisUrl',formData).then((res)=>{
    seImage.value = false
    //提示图片解析成功
    if(res.data.code === 'success'){
      seImage.value = false
      // 现在打印一下返回的信息
      sampleImageUrl.value = sampleImage.value.imageUrl
      nextTick(()=>{
        selectImgResult.value = res.data.result  
         // 先清除canvas
        clearCanvas();
        algorithmResult.value = res.data.result;
        algorithmResultMessageList.value = selectImgResult.value;
        // **调用绘制方法**
         drawBoxes();
      })

      nextTick(()=> {
        Analyse.value = false
      })
       // 将url上传接口
        //将左下角的图片切换url 
        selsetSampleImageUrl.value = sampleImage.value.imageUrl
        //  Analyse.value = false
        ElMessage({
        message: '算法解析成功',
        type: 'success',
      })
      selectBox(2)
      SelectImgDialogVisible.value = false
      }
    }) } catch (error) {
    console.error('Upload failed:', error);
    upImage.value = false
  }

}

//返回首页
const backHome = () => {
  router.push('/');
  // 清空相关图片数据
  changeAlgorithmFlag.value = false
  sampleImageUrl.value = '';
  updataSampleUrl.value = '';
  // 清理 localStorage 中的 currentScenarioID
  localStorage.removeItem('currentScenarioID');
};

const AllAlgorithmAndAlgorithmScenario = ref()
const getAllAlgorithm = () => {
  request.get("/algorithm/algorithmView").then((res) => {   
    AllAlgorithmAndAlgorithmScenario.value = res.data
  });
};


onMounted(() => {
  clearCanvas()
  // 默认选择第一个
  selectBox(1);
  getAllAlgorithm();

  // 如果 route.query 存在，则使用它初始化页面数据
  if (route.query.scenarioID) {
    pageScenarioID.value = route.query.scenarioID as string;
     smallSample.value = route.query.exampleUrl as string; // 左下角的示例图片
    sampleImageUrl.value = route.query.exampleUrl as string; // 传过来的示例图片
    algorithmResult.value =JSON.parse(JSON.parse(route.query.result as string)).result; // 传过来的结果图片
    if(algorithmResult.value){
      const img = new Image();
          img.src = sampleImageUrl.value;
          img.onload = () => { 
            drawBoxes();
          }
    }
    const result: any = route.query.resultdetail;
    if (result) {
      algorithmResultMessageList.value = JSON.parse(result).detail;
    }
    // 将 pageScenarioID 存储到 localStorage
    localStorage.setItem('currentScenarioID', pageScenarioID.value);
  } else {
    // 如果 route.query 不存在，则从 localStorage 中读取 pageScenarioID
    const savedScenarioID = localStorage.getItem('currentScenarioID');
    if (savedScenarioID) {
      pageScenarioID.value = savedScenarioID;
      // 根据 pageScenarioID 初始化 currentAlgorithm
      if (currentAlgorithm.value) {
        sampleImageUrl.value = currentAlgorithm.value.exampleUrl;
        smallSample.value = currentAlgorithm.value.exampleUrl;
        if (currentAlgorithm.value.algorithmResult) {
          algorithmResultImg.value = JSON.parse(currentAlgorithm.value.algorithmResult).result;
          algorithmResultMessageList.value = JSON.parse(currentAlgorithm.value.algorithmResult).detail;
        }
      }
    }
  }
});
  </script>
  
  <style scoped>
  .app-container {
    height: 100%;
    width: 100%;
  }
  
  .header {
    width: 100%;
    height: 10%;
    color: white;
    display: flex;
    position: relative;
  }
  
  .header-title {
    font-size: 1rem;
    font-weight: bold;
    margin-top: 5px;
  }
  
  .header-subtitle {
    font-size: 1em;
    margin-bottom: 5px;
    margin-top: 10px;
  }
  .main {
    width: 100%;
    height: 80%;
    overflow: visible;
  }
  .main-top {
    width: 100%;
    height: 75%;
    display: flex;
    overflow: hidden;

  }
  .top-left{
    height: 100%;
    width: 66%;
    background-color: rgb(216, 216, 216);
    margin-right: 5px;
    margin-bottom: 5px;
    position: relative;
  }
  .top-right{
    height: 100%;
    width: 34%;
    background-color: rgba(149, 149, 150, 0.9);
    margin-left: 5px;
    margin-bottom: 5px;
  }
  .main-bottom {
    margin-top: 10px;
    width: 100%;
    height: 25%;
    display: flex;
  }
  .bottom-left {
    height: 100%;
    width: 66%;
    margin-right: 5px;
    display: grid;
    grid-template-columns: calc(33.33% - 20px) 33.33% 33.33%;
    grid-template-rows:100%;
    gap: 10px;
  }
  .bottom-min {
    background-color: #fff;
  }
  .bottom-min2 {
    background-color: #fff;
    text-align: center;
    position: relative;
  }
  .bottom-min3 {
    background-color: #fff;
    text-align: center;
    position: relative;
  }
  .bottom-right{
    height: 100%;
    width: 34%;
    margin-left: 5px;
    background-color: #fff;
    display: flex;
    position: relative;
  }

  .scene-title {
  font-size: 1rem;
  margin: 0.5rem 0;
  color: lightblue;
  font-weight: bold;
}

/* 样式：算法网格 */
.algorithm-grid {
  padding: 7px 0;
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

/* 样式：单个算法项 */
.algorithm-item {
  flex: 0 0 32%;
  overflow: hidden;
}

/* 样式：算法名称 */
.algorithm-name {
  color: white;
  font-weight: bold;
  font-size: 0.9rem;

}
.algorithm-name:hover {
  color: skyblue;
}

  .bottom-right-left {
    flex: 1;
    height: 100%;
    position: relative;
  }
  .bottom-right-middle {
    flex: 1;
    height: 100%;
    position: relative;
    
  }
  .bottom-right-right {
    flex: 1;
    height: 100%;
    position: relative;
  }
  .demo-image__error .image-slot {
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}
/* 选中颜色的函数 */
.box {
  box-sizing: border-box;
  z-index: 1; /* 确保边框不被覆盖 */
}
.selected {
  border: 2px solid #00bfff;
  border-color: #00bfff; /* 更改选中框的边框颜色 */
}

.textChangeColor {
  color: black;
}

.textChangeColor:hover {
  color: skyblue;
}

.moreChange {
  color:#0c294c;
}
.moreChange:hover {
  color: skyblue;
}

.image-container {
  position: relative;
  width: 100%;
  height: 100%;
  z-index: 999;
}
.image-containerOne {
  width: 100%;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: none; /* 隐藏溢出的内容 */
}

.drawer-image {
  max-width: 60vw;
  max-height: 100vh;
  object-fit: contain; /* 保持图片完整，宽度或高度适应 */
}

.bounding-box-canvas {
  position: absolute;
  top: 0;
  right: 0;
  pointer-events: none;
  overflow: hidden;
}
  </style>
  